import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:developer';

/// 多次订阅:Stream,StreamController.broadcast
/// 直接创建多订阅Stream
/// 参考资料: https://blog.csdn.net/weixin_30586085/article/details/100090859
class BroadcastStreamControllerDemoHome extends StatefulWidget {
  const BroadcastStreamControllerDemoHome({Key? key}) : super(key: key);

  @override
  _BroadcastStreamControllerDemoHomeState createState() => _BroadcastStreamControllerDemoHomeState();
}

class _BroadcastStreamControllerDemoHomeState extends State<BroadcastStreamControllerDemoHome> {
  /// 创建Stream接收数据
  String s = "";

  // 流的事件订阅
  late StreamSubscription streamSubscription;

  String streamStatus = "正常";

  // 订阅次数:
  int count = 0;

  /// Stream控制器
  /// 直接创建多订阅Stream
  StreamController<String> _streamController = StreamController.broadcast(
      onListen: () {
        log("_streamController broadcast onListen");
      },
      onCancel: () {
        log("_streamController broadcast onCancel");
      },
      sync: true);

  @override
  void initState() {
    super.initState();

    // 多次订阅
    streamSubscription = _streamController.stream.listen(_onData,
        onError: _onError, onDone: _onDone, cancelOnError: false);

    // 多次订阅
    _streamController.stream.listen(_onDataTwo,
        onError: _onError, onDone: _onDone, cancelOnError: false);
  }

  @override
  void dispose() {
    super.dispose();
    if (!_streamController.isClosed) {
      _streamController.close();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("broadcast 多次订阅"),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: _addData2Stream,
      ),
      body: Container(
        margin: EdgeInsets.only(left: 15, right: 15),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              height: 15,
            ),
            Expanded(
                child: Container(
              child: SingleChildScrollView(
                child: Container(
                  child: Text(
                    "流数据: $s",
                    style: Theme.of(context).textTheme.body1,
                  ),
                ),
              ),
            )),
            SizedBox(height: 15,),
            Text(
              "功能列表:",
              style: Theme.of(context).textTheme.subtitle1,
            ),
            Text(
              "1. 基本使用",
              style: Theme.of(context).textTheme.bodyText1,
            ),
            Text(
              "2. 事件订阅",
              style: Theme.of(context).textTheme.bodyText1,
            ),
            SizedBox(
              height: 15,
            ),
            Text(
              "Stream状态: $streamStatus",
              style: Theme.of(context).textTheme.subtitle1,
            ),
            SizedBox(
              height: 25,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                FlatButton(
                  onPressed: _pauseStream,
                  child: Text("pause"),
                  color: Colors.yellowAccent,
                ),
                FlatButton(
                  onPressed: _resumeStream,
                  child: Text("resume"),
                  color: Colors.green,
                ),
                FlatButton(
                  onPressed: _cancelStream,
                  child: Text("cancel"),
                  color: Colors.lightBlue,
                ),
              ],
            ),
            SizedBox(
              height: 15,
            )
          ],
        ),
      ),
    );
  }

  /// 异步获取数据
  static Future<String> _feathData() async {
    await Future.delayed(Duration(seconds: 3));
    return "Hello Stream ~!";
    // throw "数据错误...";
  }

  /// 数据处理完成
  _onDone() {
    log("流已完成");
  }

  /// 有数据时回调
  void _onData(String event) {
    log("流数据： $event");
    refreshTextContent(event);
  }

  /// 出现错误
  _onError(error) {
    log("出现错误:$error");
  }

  void _pauseStream() {
    log("暂停Stream");
    streamSubscription.pause();
    setState(() {
      streamStatus = "pause";
    });
  }

  void _resumeStream() {
    log("继续Stream");
    streamSubscription.resume();
    setState(() {
      streamStatus = "resume";
    });
  }

  /// 取消再继续，流是不会继续往下走的
  void _cancelStream() {
    log("取消Stream");
    streamSubscription.cancel();
    setState(() {
      streamStatus = "cancel";
    });
  }

  void _addData2Stream() async {
    String data = await _feathData();
    _streamController.add(data);
  }

  void _onDataTwo(String newData) {
    log("_onDataTwo 流数据： $newData");
    refreshTextContent(newData);
  }

  void refreshTextContent(String data) {
    count++;
    setState(() {
      s = "$s + _onDataTwo: $data , num: $count";
    });
  }
}

///[log] _streamController broadcast onListen
/// [log] 流数据： Hello Stream ~!
/// [log] _onDataTwo 流数据： Hello Stream ~!
